package com.seal.yoyoshop.web;

import com.seal.yoyoshop.bin.Type;
import com.seal.yoyoshop.bin.User;
import com.seal.yoyoshop.service.TypeService;
import com.seal.yoyoshop.service.UserService;
import com.seal.yoyoshop.service.impl.TypeServiceImpl;
import com.seal.yoyoshop.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "LoginServlet", value = "/index/login")
public class LoginServlet extends HttpServlet {

    private TypeService typeService = new TypeServiceImpl();
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        导航栏
        request.setAttribute("flag",6);
        List<Type> typeList = typeService.getTypeList();
        request.setAttribute("typeList",typeList);

        request.getRequestDispatcher("/index/login.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        导航栏
        request.setAttribute("flag", 6);
        List<Type> typeList = typeService.getTypeList();
        request.setAttribute("typeList", typeList);
        //处理乱码
        request.setCharacterEncoding("UTF-8");
        //获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
//        根据用户名和密码查询用户
        User user = userService.getUserByUsernameAndPassword(username,password);
        if(user == null){//用户未查到
//            给出一个错误提示
            request.setAttribute("msg","登陆失败");
            request.getRequestDispatcher("/index/login.jsp").forward(request,response);

        }else {//登陆成功
//            request.setAttribute("msg","登陆成功");
            //获取session
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            //跳转到首页
            request.getRequestDispatcher("/index/index").forward(request,response);
        }

    }
}
